package com.sc.admin.core.bo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.admin.core.dao.SysMenuMapper;
import com.sc.admin.core.dao.SysResourceMapper;
import com.sc.admin.dto.MenuTreeDto;
import com.sc.admin.dto.ResourceTreeDto;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.enums.ApplicationEnum;
import com.sc.common.util.MyStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;

/**
 * 可复用业务对象：角色
 */
@Component
public class ResourceBo {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysResourceMapper sysResourceMapper;


    /**
     * 构建指定账号到资源权限树
     * @param accountId
     * @return
     */
    public String buildFunctionTreeByAccountId(String permissionType,Long accountId) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        JSONArray jsonArray = new JSONArray();

        // 叶子菜单code集合
        Set<String> leafNodeSet = new HashSet<>();

        List<MenuTreeDto> menuList = sysMenuMapper.findByAccountId(permissionType, ctx.getLocale().toString(), accountId);
        if (!CollectionUtils.isEmpty(menuList)) {
            for (MenuTreeDto menu : menuList) {
                if ("A100702".equals(menu.getIsParent())) {   // 叶子节点
                    leafNodeSet.add(menu.getCode());
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", menu.getCode());
                jsonObject.put("pId", menu.getPcode());
                jsonObject.put("name", menu.getDescription());
                jsonObject.put("type", ApplicationEnum.MENU_TYPE_M.getStringValue());
                jsonObject.put("checked", menu.getChecked());
                if (MyStringUtils.isBlank(MyStringUtils.null2String(menu.getPcode()))) {
                    jsonObject.put("open", true);
                }
                jsonArray.add(jsonObject);
            }
        }

        // 根据叶子菜单获取资源
        if (!CollectionUtils.isEmpty(leafNodeSet)) {
            Map<String, List<ResourceTreeDto>> resultMapAll = groupResourcesByMenuCode4account("A100401", accountId);
            for (String menuCode : leafNodeSet) {
                List<ResourceTreeDto> resourceList = resultMapAll.get(menuCode);
                if (CollectionUtils.isEmpty(resourceList)) {
                    continue;
                }
                for (ResourceTreeDto resource : resourceList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", resource.getCode());
                    jsonObject.put("pId", menuCode);
                    jsonObject.put("name", resource.getDescription());
                    jsonObject.put("type", ApplicationEnum.MENU_TYPE_R.getStringValue());
                    jsonObject.put("checked", resource.getChecked());
                    jsonArray.add(jsonObject);
                }
            }
        }
        return jsonArray.toJSONString();
    }

    /**
     * 构建组织架构里面指定岗位到资源权限树
     *
     * @param permissionType       权限类型
     * @param organizationId 岗位在组织架构里面到id
     * @return
     */
    public String buildFunctionTreeByOrganizationId(String permissionType, Long organizationId) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        JSONArray jsonArray = new JSONArray();

        // 叶子菜单编码集合
        Set<String> leafNodeSet = new HashSet<>();

        List<MenuTreeDto> menuList = sysMenuMapper.findByOrganizationId(permissionType, ctx.getLocale().toString(), organizationId);
        if (!CollectionUtils.isEmpty(menuList)) {
            for (MenuTreeDto menu : menuList) {
                if ("A100702".equals(menu.getIsParent())) {   // 叶子节点
                    leafNodeSet.add(menu.getCode());
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", menu.getCode());
                jsonObject.put("pId", menu.getPcode());
                jsonObject.put("name", menu.getDescription());
                jsonObject.put("type", ApplicationEnum.MENU_TYPE_M.getStringValue());
                jsonObject.put("checked", menu.getChecked());
                if (MyStringUtils.isBlank(MyStringUtils.null2String(menu.getPcode()))) {
                    jsonObject.put("open", true);
                }
                jsonArray.add(jsonObject);
            }
        }

        // 根据叶子菜单获取资源
        if (!CollectionUtils.isEmpty(leafNodeSet)) {
            Map<String, List<ResourceTreeDto>> resultMapAll = groupResourcesByMenuCode4organization(permissionType, organizationId);
            for (String menuCode : leafNodeSet) {
                List<ResourceTreeDto> resourceList = resultMapAll.get(menuCode);
                if (CollectionUtils.isEmpty(resourceList)) {
                    continue;
                }
                for (ResourceTreeDto resource : resourceList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", resource.getCode());
                    jsonObject.put("pId", menuCode);
                    jsonObject.put("name", resource.getDescription());
                    jsonObject.put("type", ApplicationEnum.MENU_TYPE_R.getStringValue());
                    jsonObject.put("checked", resource.getChecked());
                    jsonArray.add(jsonObject);
                }
            }
        }
        return jsonArray.toJSONString();
    }

    /**
     * 获取组织架构上指定岗位到资源，并根据menuCode分组
     * @param userType
     * @param organizationId
     * @return
     */
    public Map<String, List<ResourceTreeDto>> groupResourcesByMenuCode4organization(String userType, Long organizationId){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        Map<String,List<ResourceTreeDto>> resultMap = new HashMap<>();
        List<ResourceTreeDto> resourceList =  sysResourceMapper.findByOrganizationId(userType,ctx.getLocale().toString(),organizationId);
        if(!CollectionUtils.isEmpty(resourceList)) {
            for(ResourceTreeDto rt : resourceList){
                if(resultMap.containsKey(rt.getMenuCode())){
                    List<ResourceTreeDto> list = resultMap.get(rt.getMenuCode());
                    list.add(rt);
                    resultMap.put(rt.getMenuCode(), list);
                }else{
                    List<ResourceTreeDto> resultList = new ArrayList<>();
                    resultList.add(rt);
                    resultMap.put(rt.getMenuCode(), resultList);
                }
            }
        }
        return resultMap;
    }


    /**
     * 获取指定账号的资源，并根据menuCode分组
     * @param permissionType
     * @param accountId
     * @return
     */
    public Map<String, List<ResourceTreeDto>> groupResourcesByMenuCode4account(String permissionType, Long accountId){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        Map<String,List<ResourceTreeDto>> resultMap = new HashMap<>();
        List<ResourceTreeDto> resourceList =  sysResourceMapper.findByAccountId(permissionType,ctx.getLocale().toString(),accountId);
        if(!CollectionUtils.isEmpty(resourceList)) {
            for(ResourceTreeDto rt : resourceList){
                if(resultMap.containsKey(rt.getMenuCode())){
                    List<ResourceTreeDto> list = resultMap.get(rt.getMenuCode());
                    list.add(rt);
                    resultMap.put(rt.getMenuCode(), list);
                }else{
                    List<ResourceTreeDto> resultList = new ArrayList<>();
                    resultList.add(rt);
                    resultMap.put(rt.getMenuCode(), resultList);
                }
            }
        }
        return resultMap;
    }
}
